<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import ChefImage from '@/components/ChefImage/index.vue'
import { useThemeVars } from 'naive-ui'
import ChefPopover from './ChefPopover.vue'
import { Flame } from '@vicons/ionicons5'

import type { IChef } from '@/stores/types'

const props = defineProps<{
  chefs: IChef[]
}>()

const themeVars = useThemeVars()
const chefIds = ref<number[]>([])
const page = ref(1)
const pageSize = ref(20)

const paginatedChefs = computed(() => {
  const size = pageSize.value
  const start = (page.value - 1) * size
  return props.chefs.slice(start, start + size)
})

watch(
  () => props.chefs.length,
  (newLen) => {
    // 只有当总数量变化导致当前页超出范围时才重置
    const maxPage = Math.max(1, Math.ceil(newLen / pageSize.value))
    if (page.value > maxPage) {
      page.value = maxPage
    }
  },
)

function toggleChefSelection(id: number) {
  chefIds.value = chefIds.value.includes(id)
    ? chefIds.value.filter((chefId) => chefId !== id)
    : [...chefIds.value, id]
}
</script>

<template>
  <n-flex vertical>
    <n-flex v-if="chefs.length">
      <n-card
        class="w-[200px]"
        :class="{ selected: chefIds.includes(chef.chefId) }"
        size="small"
        v-for="chef in paginatedChefs"
        :key="chef.chefId"
        @click="toggleChefSelection(chef.chefId)"
      >
        <ChefPopover :id="chef.chefId">
          <n-flex>
            <ChefImage :id="chef.chefId" />
            <n-flex vertical :size="6">
              <b>{{ chef.name }}</b>
              <n-flex :size="0">
                <n-icon color="#E75F3E" :size="20" v-for="f in chef.rarity" :key="f">
                  <Flame />
                </n-icon>
              </n-flex>
            </n-flex>
            <i class="number">{{ chef.galleryId }}</i>
          </n-flex>
        </ChefPopover>
      </n-card>
    </n-flex>
    <n-empty v-else description="空空如也~" class="py-[24px]"></n-empty>
    <n-pagination
      v-model:page="page"
      :item-count="chefs.length"
      :page-size="pageSize"
      show-quick-jumper
    />
  </n-flex>
</template>

<style lang="scss" scoped>
$primaryColorHover: v-bind('themeVars.primaryColorHover');
.selected {
  border-color: $primaryColorHover;
  box-shadow: 0 0 4px $primaryColorHover;
}
.number {
  position: absolute;
  top: 0;
  right: 6px;
  z-index: 1;
  color: #88563e;
}
</style>